package com.acc.store.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

/**
 * jwt工具类
 */
@Slf4j
@Data
@Component

public class JWTUtils {

    //密钥

    private String secret="yangyileisacc1143";
    //Authorization

    private String header="Bearer";

    //创建token
    //传入userid
    public String createToken(Long userId) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, 1 * 30 * 60 * 1);
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId + "")
                .setIssuedAt(new Date())
                .setExpiration(calendar.getTime())
                .signWith(SignatureAlgorithm.HS256, secret);
        return builder.compact();
    }

    //校验jwt
    public Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("令牌还就那个不对:{}", e.toString());
            return null;
        }
    }

    //判断token是否过期
    public boolean judgeTokenExpiration(Date expiration) {
        return expiration.before(new Date());
    }
}
